import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/utils/event_bus.dart';
import 'package:flutter_enjoy_plus/utils/http.dart';
import 'package:flutter_enjoy_plus/utils/toast.dart';
import 'package:flutter_enjoy_plus/utils/token.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  //实现倒计时
  int _countdown = 60;
  bool _isCountingDown = false; //是否正在倒计时(标志-防止重复点击)
  Timer? _timer;
  //倒计时功能
  _startCountDown() async {
    //如果正在倒计时,终止程序执行
    if (_isCountingDown) return;
    //执行倒计时逻辑
    _isCountingDown = true; //标记倒计时的状态是进行中

    //发送请求-为了防止多次请求/多次发送(60s之内)
    final res =
        await http.get('/code', params: {'mobile': _phoneController.text});
    if (res['code'] != 10000) return ToastUtil.showError('获取验证码异常');
    ToastUtil.showSucess('获取验证码成功~');
    _codeController.text = res['data']['code'];

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdown > 1) {
          _countdown--;
        } else {
          _countdown = 60;
          _isCountingDown = false;
          _timer!.cancel(); //关闭定时器
        }
      });
    });
  }

  //手机号
  final _phoneController = TextEditingController();
  //验证码
  final _codeController = TextEditingController();

  //校验手机号
  _verifyPhone() {
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }
    //以xx开头 以xx结尾 js/arkts
    // /^1[3-9][0-9]{9}$/ 正则规则.test()

    // r作用:避免转义字符 字符串中\具有特殊含义
    //\d 0-9的数字
    RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
    if (!regExp.hasMatch(_phoneController.text)) {
      return ToastUtil.showError('请输入正确的手机号码');
    }

    _startCountDown(); //开启倒计时
  }

  //登录校验
  _login() async {
    //1.判断手机号
    //2.判断验证码
    //3.发送请求-调用登录接口
    //4.登录成功状态 10000
    //4.1存token
    //4.2提示用户
    //4.3清除定时器
    //4.4返回上一页
    if (_phoneController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }
    RegExp regExp = RegExp(r'^1[3-9]\d{9}$');
    if (!regExp.hasMatch(_phoneController.text)) {
      return ToastUtil.showError('请输入正确的手机号码');
    }
    if (_codeController.text.isEmpty) {
      return ToastUtil.showError('请输入手机号');
    }
    RegExp regExp1 = RegExp(r'^\d{6}$');
    if (!regExp1.hasMatch(_codeController.text)) {
      return ToastUtil.showError('请输入正确的验证码');
    }
    final res = await http.post('/login', {
      'mobile': _phoneController.text,
      'code': _codeController.text,
    });
    if (res['code'] != 10000) return ToastUtil.showError('登录异常,请稍后再试~');
    ToastUtil.showSucess('登录成功');
    final tokenmanager = TokenManager();
    tokenmanager.setToken(res['data']['token']);
    _timer?.cancel();
    // 发布事件
    eventBus.fire(RefreshMine());
    // ignore: use_build_context_synchronously
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('登录'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: Container(
            padding: const EdgeInsets.all(20),
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              const Row(
                children: [
                  Text('登录',
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold))
                ],
              ),
              const SizedBox(height: 10),
              const Row(
                children: [
                  Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))
                ],
              ),
              const SizedBox(height: 30),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: TextField(
                      decoration: const InputDecoration(
                        labelText: '手机号',
                        hintText: '请输入手机号',
                      ),
                      controller: _phoneController,
                      //手机号输入
                      keyboardType: TextInputType.phone,
                      //最大字数
                      maxLength: 11,
                    ),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shadowColor: Colors.transparent,
                      foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      // 开启倒计时效果
                      // _startCountDown();
                      _verifyPhone();
                    },
                    child: _isCountingDown
                        ? Text(
                            '$_countdown s后重新获取验证码',
                            style: const TextStyle(color: Colors.red),
                          )
                        : const Text('获取验证码'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              TextField(
                decoration: const InputDecoration(
                  labelText: '验证码',
                  hintText: '请输入6位验证码',
                ),
                controller: _codeController,
                //手机号输入
                keyboardType: TextInputType.number,
                //最大字数
                maxLength: 6,
              ),
              const SizedBox(height: 8),
              const Row(children: [
                Text('未注册手机号经验证后将自动登录',
                    style: TextStyle(fontSize: 12, color: Colors.grey)),
              ]),
              const SizedBox(height: 50),
              Row(children: [
                Expanded(
                    child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _login();
                  },
                  child: const Text('登录',
                      style: TextStyle(color: Colors.white, fontSize: 20)),
                ))
              ])
            ])));
  }
}
